#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#define BUFSIZE 1024
int main(int argc, char *argv[]) {

    int sockfd;
    struct sockaddr_in serv;

    if(argc < 3) {
        printf("invalid format, no port\n");
        return -1;
    }


    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket");
        return -1;
    }
    memset(&serv, 0, sizeof(struct sockaddr_in));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(atoi(argv[2]));
    //serv.sin_addr.s_addr = htonl(INADDR_ANY); // 本机任意一个地址
    inet_pton(AF_INET, argv[1], &serv.sin_addr);

    if( bind(sockfd, (struct sockaddr *)&serv, sizeof(serv)) < 0) {
        perror("bind");
        return -1;
    }

    while(1) {
        int n;
        char rcvbuf[BUFSIZE], cliaddr[16];
        struct sockaddr_in client;
        socklen_t len = sizeof(client);

        n = recvfrom(sockfd, rcvbuf, BUFSIZE, 0 , (struct sockaddr *)&client, &len);
        if (n > 0) {
            rcvbuf[n] = 0;
            inet_ntop(AF_INET, &client.sin_addr.s_addr, cliaddr, sizeof(cliaddr));

            printf("recvfrom %s:%d content: %s", cliaddr, ntohs(client.sin_port), rcvbuf);
            sendto(sockfd, rcvbuf, n, 0, (struct sockaddr *)&client, len);
        }
    }
    return 0;
}


